package com.example.bledemo.util;

import android.util.Log;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 网络工具类
 */
public class NetworkUtils {
    
    private static final String TAG = "NetworkUtils";
    private static final int CONNECTION_TIMEOUT = 5000; // 5秒超时
    
    /**
     * 测试TCP连接
     * @param ipAddress IP地址
     * @param port 端口号
     * @return 连接结果
     */
    public static ConnectionResult testTcpConnection(String ipAddress, int port) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddress, port), CONNECTION_TIMEOUT);
            return new ConnectionResult(true, "连接成功");
        } catch (UnknownHostException e) {
            Log.e(TAG, "UnknownHostException: " + e.getMessage());
            return new ConnectionResult(false, "无法解析主机地址");
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
            return new ConnectionResult(false, "连接失败：" + e.getMessage());
        } finally {
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭socket失败: " + e.getMessage());
                }
            }
        }
    }
    
    /**
     * 连接结果类
     */
    public static class ConnectionResult {
        private final boolean success;
        private final String message;
        
        public ConnectionResult(boolean success, String message) {
            this.success = success;
            this.message = message;
        }
        
        public boolean isSuccess() {
            return success;
        }
        
        public String getMessage() {
            return message;
        }
    }
} 